const fs = require('fs');

function readFile(fileName) {
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, (err, data) => {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

function* gen() {
    let a = yield readFile(__dirname + '/1.txt');
    let b = yield readFile(__dirname + '/2.txt');
    let c = yield readFile(__dirname + '/3.txt');
    return a + b + c;
}

/* let s = gen();
s.next()
    .value.then(data => {
        console.log(String(data));
        return s.next(data).value;
    })
    .then(data => {
        console.log(String(data));
        return s.next(data).value;
    })
    .then(data => {
        console.log(String(data));
        console.log(typeof data);
        return s.next(data).value;
    })
    .then(data => {
        console.log(String(data));
        console.log(typeof data);
        return s.next().value;
    }); */
//自动执行器,优秀实现
function run(gen) {
    var g = gen();

    function next(data) {
        var result = g.next(data);
        if (result.done) {
            console.log(result.value);
            return result.value;
        }
        result.value.then(function(data) {
            console.log(String(data));
            next(data);
        });
    }
    next();
}
//run(gen);
//自动执行器，有缺陷
async function run1(gen) {
    let g = gen();
    let result = g.next();
    while (!result.done) {
        let data1 = null;
        let p = result.value.then(data => {
            console.log('a');
            data1 = String(data);
            console.log(String(data));
        });
        await p;
        console.log('b');
        result = g.next(data1);
    }
    console.log(result.value);
}
